import { FastifyPluginAsync } from "fastify";
import { generateTimestampedInviteCode } from "../../../utils/inviteCode";
import { CreateRoomRequest, InviteMember, RoomDocument } from "./type";

const createRoomRoutes: FastifyPluginAsync = async (
  fastify,
  opts,
): Promise<void> => {
  fastify.post("/create-room", async (request, reply) => {
    const db = fastify.mongo.db;
    if (!db) {
      return reply.code(500).send({ error: "MongoDB not connected" });
    }

    // 类型断言请求体
    const { roomNumber, orderNo, inviteCode, messages, ua, fingerprintId } =
      request.body as CreateRoomRequest;

    if (!/^\d{2}-\d{2}-\d{4}$/.test(roomNumber)) {
      return reply.code(400).send({ error: "roomNumber format is invalid" });
    }
    if (!orderNo) {
      return reply.code(400).send({ error: "parameters are required" });
    }
    try {
      // 检查房间是否已存在
      const existingRoom = await db
        .collection<RoomDocument>("rooms")
        .findOne({ roomNumber });

      if (existingRoom) {
        // 检查订单号是否已存在
        const orderExists = existingRoom.orderNo === orderNo;

        if (orderExists) {
          return reply.code(409).send({
            success: false,
            error: "订单号已存在",
            message: "该订单号已被使用，请勿重复提交",
          });
        }
      }

      // 生成唯一邀请码
      const uniueInviteCode = existingRoom?.inviteCode
        ? existingRoom.inviteCode
        : generateTimestampedInviteCode();

      // 创建新房间
      const newRoom = {
        roomNumber,
        orderNo,
        messages,
        createdAt: Date.now(),
        updatedAt: Date.now(),
        ua,
        fingerprintId,
        inviteMembers: [],
        inviteCode: uniueInviteCode, // 添加邀请码
      };

      const result = await db
        .collection<RoomDocument>("rooms")
        .insertOne(newRoom);
      // 如果请求中包含邀请码，将新房间的 orderNo 添加到拥有此邀请码的房间的 inviteMembers 中
      if (inviteCode) {
        const memberInfo: InviteMember = {
          updatedAt: Date.now(),
          id: result.insertedId.toString(), // 使用 MongoDB 生成的 _id
          roomNumber,
        };
        await db.collection<RoomDocument>("rooms").updateOne(
          { inviteCode },
          {
            $addToSet: { inviteMembers: memberInfo },
            $set: { updatedAt: Date.now() },
          },
        );
      }
      return reply.code(201).send({
        success: true,
        data: {
          roomNumber,
          orderNo,
          inviteCode: uniueInviteCode,
        },
        message: "订单创建成功",
      });
    } catch (error) {
      fastify.log.error(error);
      return reply.code(500).send({ error: "Internal Server Error" });
    }
  });
};

export default createRoomRoutes;
